use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(Product::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(Product::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(Product::Sku).string().not_null().unique_key())
                    .col(ColumnDef::new(Product::Price).decimal().not_null())
                    .col(ColumnDef::new(Product::ComparePrice).decimal())
                    .col(ColumnDef::new(Product::CostPrice).decimal())
                    .col(ColumnDef::new(Product::TrackInventory).boolean().not_null())
                    .col(ColumnDef::new(Product::Weight).decimal())
                    .col(ColumnDef::new(Product::Status).string().not_null())
                    .col(ColumnDef::new(Product::FeaturedImageUrl).string())
                    .col(ColumnDef::new(Product::PublishedAt).timestamp_with_time_zone())
                    .col(ColumnDef::new(Product::CategoryId).uuid())
                    .col(ColumnDef::new(Product::BrandId).uuid())
                    .col(ColumnDef::new(Product::CreatedAt).timestamp_with_time_zone().not_null())
                    .col(ColumnDef::new(Product::UpdatedAt).timestamp_with_time_zone().not_null())
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk-product-category_id")
                            .from(Product::Table, Product::CategoryId)
                            .to(Category::Table, Category::Id)
                            .on_delete(ForeignKeyAction::SetNull),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk-product-brand_id")
                            .from(Product::Table, Product::BrandId)
                            .to(Brand::Table, Brand::Id)
                            .on_delete(ForeignKeyAction::SetNull),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(Product::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum Category {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum Brand {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum Product {
    Table,
    Id,
    Sku,
    Price,
    ComparePrice,
    CostPrice,
    TrackInventory,
    Weight,
    Status,
    FeaturedImageUrl,
    PublishedAt,
    CategoryId,
    BrandId,
    CreatedAt,
    UpdatedAt,
}